package com.quaidi.smartlocker.controller;

import com.quaidi.smartlocker.common.Result;
import com.quaidi.smartlocker.enums.UserRole;
import com.quaidi.smartlocker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 
 * @author QuaiDi
 * @since 2025-08-26
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password, 
            HttpSession session,
            HttpServletRequest request) {
        try {
            UserRole role = userService.login(username, password, session, request);
            
            Map<String, Object> result = new HashMap<>();
            result.put("role", role.getCode());
            result.put("roleName", role.getDescription());
            result.put("isAdmin", role == UserRole.ADMIN);
            
            return Result.success("登录成功", result);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public Result<Map<String, Object>> getCurrentUser(HttpSession session) {
        UserRole role = userService.getCurrentUserRole(session);
        
        Map<String, Object> result = new HashMap<>();
        result.put("role", role.getCode());
        result.put("roleName", role.getDescription());
        result.put("isAdmin", role == UserRole.ADMIN);
        
        return Result.success(result);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        userService.logout(session);
        return Result.success("登出成功");
    }
}